//
//  TSZPhotoBrowserCollection.swift
//  微博天下
//
import UIKit

import SVProgressHUD
//可重用标识符

private let TSZPhotoBrowserCollectionCellIditify = "TSZPhotoBrowserViewCell"

class TSZPhotoBrowserCollection: UIViewController {
    
    //MARK: 属性
    var urls: [NSURL]?
    //当前索引
    var selectIndex: Int = 0
//    
    init(urls: [NSURL] , index: Int){
        self.urls = urls
        selectIndex = index
        //调用父类的构造函数
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()

    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        //跳转用户选中的图片
        let indexPath = NSIndexPath(forItem: selectIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    //MARK: - 构造函数
    override func loadView() {
        
        var screenBounds = UIScreen.mainScreen().bounds
        screenBounds.size.width += 20
        
        view = UIView(frame: screenBounds)
        //设置 UI
        setupUI()
    }
    
    //MARK: - 按钮的监听方法
    func save(){
       //获取你所点击的那一张照片
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! TSZPhotoCollectionCell
        //判断cell中是否有图片
        guard let image = cell.imageView.image else{
            return
        }
        
        //保存
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinisedSaveWithError:contextInfo:", nil)
    }
    // MARK:保存图片的方法
    func image(image: UIImage , didFinisedSaveWithError error:NSError? ,contextInfo: AnyObject?){
        //记住 要打印错误 
        print(error)
        
        let msg = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showErrorWithStatus(msg)
    }
    
    func close(){
        
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    private func  setupUI(){
        //1、添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        //2、自动布局
        
        collectionView.frame = view.bounds
        let rect = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 40, width: 100, height: 32)
        closeButton.frame = CGRectOffset(rect, 8, 0)
        saveButton.frame = CGRectOffset(rect, UIScreen.mainScreen().bounds.width - rect.width - 8, 0)
        
        //监听方法
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        //准备UI
        prepareCollectionView()
    }
    
    //准备collectionView
    private func prepareCollectionView(){
        
        collectionView.registerClass(TSZPhotoCollectionCell.self, forCellWithReuseIdentifier: TSZPhotoBrowserCollectionCellIditify)
        
        collectionView.dataSource = self
        
        
        // 设置布局
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
        
    }
    
    //MARK: - 懒加载
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    // MARK: - 视图的缩放比例
    private var photoScale: CGFloat = 1
    
    
}

//MARK: 实现代理方法dataSource TSZPhotoCollectionCellDelegate

extension  TSZPhotoBrowserCollection: UICollectionViewDataSource , TSZPhotoCollectionCellDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls!.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(TSZPhotoBrowserCollectionCellIditify, forIndexPath: indexPath) as! TSZPhotoCollectionCell
        
        cell.photoDelegate = self
        cell.imageURL = urls![indexPath.item]
        return cell
    }
    //MARK: TSZPhotoCollectionCellDelegate的代理方法
    func photoCellZoom(scale: CGFloat) {
        
        //交互式转场
        photoScale = scale
        
        //TODO: 设置控件的隐藏
        hiddenController(scale < 1)
        //开始转场
        if scale < 1.0 {
            startInteractiveTransition(self)
            
        }else { //还原
            view.transform = CGAffineTransformIdentity
            view.alpha = 1.0
        }
    }
    
    //缩放完成
    func photoCellEndZoom() {
        if photoScale < 0.75 {
            completeTransition(true)
        }else {
            
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1
                }, completion: { (_) -> Void in
                    self.photoScale = 1
                    self.hiddenController(false)
            })
        }
    }
    
    
    //当前显示的图像
    func currentImageView()  -> UIImageView{
        let cell = collectionView.cellForItemAtIndexPath(currentImageIndex()) as! TSZPhotoCollectionCell
        return cell.imageView
    }
    
    //当前图像的索引
    func currentImageIndex() ->NSIndexPath {
        return collectionView.indexPathsForVisibleItems().last!
    }
    
    //隐藏控件
    private func hiddenController(hidden: Bool) {
        collectionView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
        closeButton.hidden = hidden
        saveButton.hidden =  hidden
    }
}

//MARK: - 

extension TSZPhotoBrowserCollection: UIViewControllerInteractiveTransitioning{
    
    //开始交互转场
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        //设置形变
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        //设置透明度
        view.alpha = photoScale
    }
}

//MARK: UIViewControllerContextTransitioning ， 这个代理方法提供了场所所需要的任何细节
extension TSZPhotoBrowserCollection: UIViewControllerContextTransitioning{
    
    //结束转场动画
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //视图容器的协议的方法实现
    
    func containerView() -> UIView? { return view.superview }
    func isAnimated() -> Bool {
        return true
    }
    func isInteractive() -> Bool {
        return true
    }
    func transitionWasCancelled() -> Bool {
        return  false
    }
    func presentationStyle() -> UIModalPresentationStyle {
        return UIModalPresentationStyle.Custom
    }
    
    func updateInteractiveTransition(percentComplete: CGFloat){}
    func finishInteractiveTransition(){}
    func cancelInteractiveTransition(){}
    
    func viewControllerForKey(key: String) -> UIViewController?{
        return self
    }
    
    func viewForKey(key: String) -> UIView?{
        return view
    }
    
    func targetTransform() -> CGAffineTransform{
        return CGAffineTransformIdentity
    }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect{
        return CGRectZero
    }
    
    func finalFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }

}

